package v2ray

import (
	"gitee.com/yysf-xin/dproxy/pkg/db"
	"gitee.com/yysf-xin/dproxy/pkg/model"
	"gitee.com/yysf-xin/dproxy/pkg/tools"
	"gitee.com/yysf-xin/dproxy/pkg/v2ray/clash"
	"github.com/robfig/cron/v3"
	"net/http"
	"time"
)

type Switcher interface {
	DoSwitch(id uint) error
}
type clashClean struct {
	db     *db.Client
	dialer *Dialer
	sw     Switcher
	cfg    *model.CornConfig
}

func NewClashCleanJon(db *db.Client, dialer *Dialer, sw Switcher, cfg *model.CornConfig) cron.Job {
	return &clashClean{
		db:     db,
		dialer: dialer,
		sw:     sw,
		cfg:    cfg,
	}
}

func (c *clashClean) Run() {
	var cList []*clash.ConfigClash
	var id uint
	var hasSet bool
	if c.dialer.Handler != nil {
		CanUse, err := DoTest(&http.Transport{
			DialContext:       c.dialer.DialContext,
			DisableKeepAlives: true,
		})
		if CanUse {
			if c.cfg.Param == "only_check" {
				return
			}
			hasSet = true
		}
		if err != nil {
			tools.Log.Println(err)
		}
	}
	task := NewCheckClashTask()

	for i := 0; i < 2; i++ {
		err := c.db.Db.Where("can_use > 0 and id > ?", id).Limit(100).Find(&cList).Error
		if len(cList) == 0 {
			break
		}
		id = cList[len(cList)-1].Id
		if err == nil {
			task.Target.Proxies = cList
			task.CheckClash(c.dialer.Ins, c.db)
			if task.FirstCanUseId != 0 && !hasSet {
				err = c.sw.DoSwitch(task.FirstCanUseId)
				if err != nil {
					hasSet = true
				}
			}
		}
		if err != nil {
			tools.Log.Println(err)
			break
		}
		cList = cList[:0]
	}
	timeBefore := time.Now().AddDate(0, 0, -7)
	c.db.Mux.Lock()
	c.db.Db.Where("id <= ? and can_use <= 0 and created_at < ?", id, timeBefore).Delete(&clash.ConfigClash{})
	//c.db.Db.Where(
	//	"id in (select i.id from proxy_infos i left join proxy_clash c on c.id = i.target where i.type = ? and c.id is null)",
	//	model.CLASH).Delete(&model.ProxyInfo{})
	//c.db.Db.Where(
	//	"id in (select i.id from proxy_histories i left join proxy_clash c on c.id = i.target where c.id is null)",
	//	model.CLASH).Delete(&model.ProxyHistory{})
	c.db.Mux.Unlock()
}
